<template>
  <div style="height: 100%; width: 100%; position: relative;">
    <div style="height: 100%; height: 100%; position: relative" ref="D3_dom">
    </div>
    <div class="lerg" v-if="lerg">
      <ul style="display: flex;">
        <li><img :src="ImgWanger">出现预警</li>
        <li>
          <div class="radius"></div>评标专家
        </li>
        <li>
          <div class="radius"></div>招标代理
        </li>
        <li>
          <div class="radius"></div>甲方代表
        </li>
        <li>
          <div class="radius"></div>工作人员
        </li>
      </ul>
    </div>
    <div class="lerg" v-if="gzrylerg">
      <ul style="display: flex;">
        <li><img :src="ImgWanger">出现预警</li>
      </ul>
    </div>
    <div class="tools">
      <ul>
        <li @click="handleTools(1)">
          <svg class="iconfontSvg" aria-hidden="true">
            <use xlink:href="#icon-fangda"></use>
          </svg>

        </li>
        <li @click="handleTools(2)">
          <svg class="iconfontSvg" aria-hidden="true">
            <use xlink:href="#icon-suoxiao"></use>
          </svg>
        </li>
        <li @click="handleTools(3)">
          <svg class="iconfontSvg" aria-hidden="true">
            <use xlink:href="#icon-quanping"></use>
          </svg>
        </li>
      </ul>
    </div>
    <audio ref="audioPlayer" muted :controls="false">
      <source src="~@/views/witness/components/Object3D/canvas/警报声.mp3"  type="audio/mpeg">
    </audio>
    <!-- 模型加载进度条 -->
    <div id="progress-bar">
      <div id="progress"></div>
    </div>
  </div>
</template>
<script>
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import { CSS2DObject } from 'three/examples/jsm/renderers/CSS2DRenderer.js';
import { CSS2DRenderer } from 'three/examples/jsm/renderers/CSS2DRenderer.js';
import { EffectComposer } from "three/examples/jsm/postprocessing/EffectComposer.js"
import { RenderPass } from "three/examples/jsm/postprocessing/RenderPass.js"
import { OutlinePass } from "three/examples/jsm/postprocessing/OutlinePass.js"
import { OutputPass } from 'three/examples/jsm/postprocessing/OutputPass.js';
import { LineGeometry } from "three/examples/jsm/lines/LineGeometry.js"
import { Line2 } from "three/examples/jsm/lines/Line2.js"
import { LineMaterial } from "three/examples/jsm/lines/LineMaterial";
import { GUI } from "three/examples/jsm/libs/lil-gui.module.min"
import { TextGeometry } from 'three/examples/jsm/geometries/TextGeometry.js';
import { Tween, Group } from '@tweenjs/tween.js'
import * as GeometryUtils from 'three/examples/jsm/utils/GeometryUtils'
import { createTextSprite } from '@/views/witness/components/Object3D/canvas/utils'
import Model3D from "@/views/witness/components/Object3D/canvas/model_3D.js"; //模型对象
import louceng_JSON from "@/views/witness/components/Object3D/canvas/room.json"
// import dayjs from "dayjs";
const model3D = new Model3D(['标注','预警','楼层'])

export default {
  props: {
    onGetPersColor: {
      type: Function,
      default: () => []
    },
    xmName: {
      type: String,
      default: ''
    },
    onGetWanger: {
      type: Function,
    },
    onGetProData:{
      type:Function
    },
    onStart:{
      type:Function
    },
    lerg: Boolean,
    gzrylerg: Boolean,
    progress: Boolean,
  },
  components: {
    // TouimgComponent,
    // easyPlayer,
  },
  data() {
    return {
      state:model3D.state,
      playerIsShow: false,
      videoUrl: '',
      louceng: '十楼',
      ImgWanger: require('@/views/witness/components/Object3D/canvas/告警.png'),
      //播放器
      isSpeed: 1,
      isPlay: false,
      longTime: 0, // 轨迹总时长
      timeStart: 'YYYY-MM-DD 00:00:00', // 轨迹开始时间
      // 默认头像
      // touxianglist:[require('@/assets/imgs/dp/专家.png'),require('@/assets/imgs/dp/专家2.png'),require('@/assets/imgs/dp/专家3.png')],
      D3data: {},
      // peopList,
      curItemMsg: {
      },
      WangerMsgData: '',
      Wangerdata: [],
      peopleList: [],
      textarea: "",
      pos: {
        x: 0,
        y: 0,
        z: 0
      },
      positions: [], // 全部数据
      pointsData: [], // 全部数据传给子组件 轨迹
      points: [] // 部分数据
    };
  },
  watch:{
   'state.currentProgress':(newval,oldval)=>{
    const percentDiv = document.getElementById("progress"); // 获取进度条元素
    percentDiv.style.width = newval * 400 + "px"; //进度条元素长度
    percentDiv.style.textIndent = newval * 400 + 5 + "px"; //缩进元素中的首行文本
    // Math.floor:小数加载进度取整
    percentDiv.innerHTML = Math.floor(newval * 100) + '%'; //进度百分比
    
   }
  },
  created() {
   
  },
  methods: {
    async getdata(){
     await model3D.loadAllModels()
     document.getElementById("progress-bar").style.display = 'none';
     this.onStart()
    },
    // 显示隐藏 预警  人员  房间占用
    handleIsShow(item){
      const {keys,disabled}  = item
      const allMesh = this.D3data.scene.getObjectByName('全部')
      keys.forEach(e=>{
        const item = allMesh.getObjectByName(e)
        item.visible = disabled
      })
   
      
      

    },
    // 
    setRoomDate(data) {
      const Group_rooms = this.D3data.scene.getObjectByName('场地房间')
      const louceng_all = [ ... louceng_JSON['十楼'],...louceng_JSON['十二楼']]
      const gltfDitu = model3D.getObjectByName('标注')
      gltfDitu.scale.set(2,2,2)
      gltfDitu.rotation.x = THREE.MathUtils.degToRad(90);
      gltfDitu.traverse( (child)=> {
        if (child.isMesh) {
          // //模型阴影
          child.castShadow = true;
          child.material.emissive = new THREE.Color('#ffffff'); // 绿色自发光
          child.material.emissiveIntensity = 1; // 调整强度
          child.material.emissiveMap = child.material.map;
        }
      });
      data.forEach(e=>{
       const room =  louceng_all.find(x=>x.id === e.uwbAreaId)
       if(!room) return 
        const obj = gltfDitu.clone()
        let color =  new THREE.Color(e.dataType === 'KB'? 0xffff00 : '#ffffff')

        obj.traverse((child)=>{
          if (child.isMesh) {
            child.material  = child.material.clone()
            child.material.emissive = color; // 绿色自发光
            child.material.emissiveIntensity = 1; // 调整强度
            child.material.emissiveMap = child.material.map;
          }
          child.userData =  e
        })
        obj.position.set(room.x,room.y,room.z)
        obj.name ='项目标志'
        Group_rooms.add(obj)
      })
    },

    // 出现警告
    setWangerRadiusPoints(xw,data){
      const  Group_wanger = this.D3data.scene.getObjectByName('预警组')
      const { personName ,id ,xyz,floorName} = data
      const gltfYujing = model3D.getObjectByName('预警')
    
      gltfYujing.traverse( (child) =>{
      if (child.isMesh) {
        // //模型阴影
        child.castShadow = true;
        child.material.emissive = new THREE.Color('#ffffff'); // 绿色自发光
        child.material.emissiveIntensity = 1.6; // 调整强度
        child.material.emissiveMap = child.material.map;
      }
    });
      const add  = () =>{
        const newCircle = gltfYujing.clone()
        newCircle.name = id
        newCircle.traverse((child)=>{
          // if (child.isMesh) {
          //   child.material  = child.material.clone()
          //   child.material.emissive = color; // 绿色自发光
          //   child.material.emissiveIntensity = 1; // 调整强度
          //   child.material.emissiveMap = child.material.map;
          // }
          child.userData =  data
        })
        // const WangerBG = meshWangerBG.clone()
        // WangerBG.visible = false
        // WangerBG.name = '弹出框'
        // const text = createText(personName, 8)
        // const button = createText('查看', 8)
        // button.name = '查看'
        // button.data = data
        // text.position.set(-12,0,0)
        // button.position.set(12,0,0)
        // WangerBG.add(text).add(button)
        // WangerBG.position.set(0,12,0)
        // newCircle.add(WangerBG)
        let [x,y]  = xyz
        let z = 1
        if(floorName ==='十二楼'){
          z = 26
        }
        newCircle.position.set(x, y, z)
        Group_wanger.add(newCircle)
      }

      const remove = () =>{
        Group_wanger.remove(Group_wanger.getObjectByName(id))
       
      }
    
      if(xw === 'add'){
      
          add()
      }
      if(xw === 'remove'){
        remove()
      }
  
    },
      // 多种类型人员
    setPeopleRadiusPoints(xw,data){
        console.log('data',data);
      const TYPE = {
        'ZJ':{
          color:'#68F60C',
          name:'评标专家组',
        },
        'ZBDL':{
          color:'#FFC30A',
          name:'招标代理组'
        },
        'JD':{
          color:'#EB31D9',
          name:'甲方代表组'
        },
        'GZRY':{
          color:'#FFFFFF',
          name:'工作人员组'
        }
      }
   
      const name = TYPE[data.personType].name
      const Color = TYPE[data.personType].color
      const floorName =  data.trackList[0].floorName
      let z = 1;
      if(floorName === '十二楼'){
        z = 26
      }
      const [x,y] = data.trackList[0].pos
      const  Group =  this.D3data.scene.getObjectByName(name)
      if(!Group) return 
      const personId = data.personId
      const perMesh = Group.getObjectByName(personId)
      // console.log('perMesh',perMesh);
      
      const add = () =>{
        console.log(1111);
        
        const geometry = new THREE.SphereGeometry(0.4, 10, 10); // 半径为1，分段数为32   
        const color = new THREE.Color(Color)
        const material = new THREE.MeshBasicMaterial({ color, side: THREE.DoubleSide });// 创建材质
        const circleMesh = new THREE.Mesh(geometry, material);
              circleMesh.name = personId
              circleMesh.userData = data
              circleMesh.isPeople = true
              circleMesh.position.set(x,y,z)
              Group.add(circleMesh)
      }
      const edit = () => {
        perMesh.position.set(x,y,z)
      }
      const remove = () =>{
        console.log('删除');
        Group.remove(Group.getObjectByName(personId))
      }

      if(xw === 'remove'){
        remove()
        return 
      }
      if(perMesh){
        edit()
      }else{
        add()
      }
    

    },
    // 添加实时点位
    // addProViewDataPoint(data) {
    //   const child = model.getObjectByName(data.id)
    //   const { x, y, z } = data.xyz
    //   child.position.set(x, y, z)
    // },
    initDiv() {
      // 获取dom节点
      const width = this.$refs["D3_dom"].offsetWidth;
      const height = this.$refs["D3_dom"].offsetHeight;
      //场景
      const scene = new THREE.Scene();
      let selectedObjects = []
      // scene.background = new THREE.Color('#7b7e80');
      const model = model3D.getObjectByName('楼层')
      const Group = new THREE.Group()
      Group.position.set(0, 0, 0);
      Group.name = "全部";
      Group.add(model)
      scene.background = null;
      scene.add(Group);
      // model.children[0].geometry.translate(985/2,277/2,0);
      // 总辅助坐标系
      // const axesHelper = new THREE.AxesHelper(100);
      // scene.add(axesHelper);
      // 添加一个辅助网格地面 1468 × 400
      // const gridHelper = new THREE.GridHelper(1468, 400, 0x004444, 0x004444);
      // scene.add(gridHelper);

      //光源设置
      const directionalLight = new THREE.DirectionalLight(0xffffff, 2);
      directionalLight.position.set(100, 50, 50);
      scene.add(directionalLight);


        const light12 = new THREE.PointLight( 0xffffff, 200);
        light12.position.set( 48, 18, 8 );
        scene.add( light12 );

        const light10 = new THREE.PointLight( 0xffffff, 200);
        light10.position.set( 48, 18, 32 );
        scene.add( light10 );

      const ambient = new THREE.AmbientLight(0xffffff, 1);
      scene.add(ambient);
      //渲染器和相机
      const camera = new THREE.PerspectiveCamera(30, width / height, 1, 3000);
      camera.position.set(50, -66, 70);
      camera.lookAt(50, 30, 0);
      const renderer = new THREE.WebGLRenderer();
      renderer.setSize(width, height);
      renderer.setClearAlpha(0);
      renderer.setPixelRatio(window.devicePixelRatio); //防止输出模糊
      renderer.outputEncoding = THREE.sRGBEncoding;
      this.$refs["D3_dom"]?.appendChild(renderer.domElement);
      // document.body.appendChild(renderer.domElement);
      // const div = document.getElementById ('tag');、
      // 将css元素添加到模型中
      //      const Div_box_people =  this.$refs["box_people"]
      // const Div_model_box_people = new CSS2DObject(Div_box_people);
      //         //改变图片网格模型顶点坐标
      // //       // Div_model_box_people.position.set(pos.getX(0),pos.getY(0),pos.getZ(0));
      // model.children[0].add(Div_model_box_people);  //插入css弹框
      // css2渲染器
      const css2Renderer = new CSS2DRenderer();
      css2Renderer.setSize(width, height);
      css2Renderer.domElement.style.position = 'absolute';
      css2Renderer.domElement.style.top = '0px';
      // css2Renderer.domElement.style.display='none';
      css2Renderer.domElement.style.pointerEvents = 'none';
      this.$refs["D3_dom"]?.appendChild(css2Renderer.domElement);
      //后处理
      // 创建渲染器通道
      // const composer = new EffectComposer(renderer);
      // const renderPass = new RenderPass(scene, camera);
      // composer.addPass(renderPass);
      // const outputPass = new OutputPass();
      // composer.addPass(outputPass);
      // 创建outlinePass通道
      // const v2 = new THREE.Vector2(width, height);
      // const outlinePass = new OutlinePass(v2, scene, camera);
      // outlinePass.visibleEdgeColor.set(0x00ffff);
      // outlinePass.edgeThickness = 4;
      // console.log();
      // const xx = model.children[0].children[0]
      // outlinePass.selectedObjects = [ xx];
      // outlinePass.selectedObjects = model.children[0].children;
      // outlinePass.edgeStrength = 6;
      // composer.addPass(outlinePass);

      function addSelectedObject(object) {
        selectedObjects = [];
        selectedObjects.push(object);
      }
      // renderer.domElement.addEventListener('mousemove',(event)=>{
      //   const px = event.offsetX;
      //   const py = event.offsetY;
      //   const x = (px / width) * 2 - 1;
      //   const y = -(py / height) * 2 + 1;
      //   const raycaster = new THREE.Raycaster();
      //   raycaster.setFromCamera(new THREE.Vector2(x, y), camera)
      //   const  Group_wanger = model.getObjectByName('预警组')
      //   const intersects = raycaster.intersectObjects(Group_wanger.children)
      //   if (intersects.length > 0 && intersects[0].object.children.length>0) {
      //     if(intersects[0].object.children[0].name === '弹出框'){
      //       intersects[0].object.children[0].visible = true
      //     //   setTimeout(() => {
      //     //   intersects[0].object.children[0].visible = false
      //     // }, 1000 * 10);
      //     }
      //   }else{

      //   }

      // })
      // 坐标拾取
      renderer.domElement.addEventListener('click', (event) => {
        const px = event.offsetX;
        const py = event.offsetY;
        const x = (px / width) * 2 - 1;
        const y = -(py / height) * 2 + 1;
        const raycaster = new THREE.Raycaster();
        this.onGetProData(null)
        raycaster.setFromCamera(new THREE.Vector2(x, y), camera)
        const Group_wanger =  this.D3data.scene.getObjectByName('预警组')
         const intersects_wanger = raycaster.intersectObjects(Group_wanger.children)
         if (intersects_wanger.length > 0) {
          this.onGetProData({...intersects_wanger[0].object.userData},'预警')
            
         }

        // const intersects = raycaster.intersectObjects(Group_wanger.children)
        // if (intersects.length > 0) {
        //   if (intersects[0].object.name === '警告') {
        //     this.onGetWanger(intersects[0].object.id_waring)
        //   }
        //   if (intersects[0].object.name === '警告标志') {
        //     intersects[0].object.parent.children[0].visible = !intersects[0].object.parent.children[0].visible
        //   }
        //   if (intersects[0].object.name === '弹出框' && intersects[0].object.visible) {
        //     this.onGetWanger('触发父组件')
        //   }
        // }
        // 查看项目
        const Group_rooms =  this.D3data.scene.getObjectByName('场地房间')
        const intersectsY = raycaster.intersectObjects(Group_rooms.children)
   
        if(intersectsY.length > 0){
          if(intersectsY[0].object.name === '001-0-1'){
            this.onGetProData({...intersectsY[0].object.userData},'项目')
          }
        }





     

        //查看人员
        const Group_people_PBZJ =  this.D3data.scene.getObjectByName('评标专家组')
        const Group_people_ZBDL =  this.D3data.scene.getObjectByName('招标代理组')
        const Group_people_JFDB =  this.D3data.scene.getObjectByName('甲方代表组')
        const Group_people_GZRY =  this.D3data.scene.getObjectByName('工作人员组')
        const intersects_people = raycaster.intersectObjects([Group_people_PBZJ,Group_people_ZBDL,Group_people_JFDB,Group_people_GZRY])
        if(intersects_people.length > 0){
          if(intersects_people[0].object.isPeople){
            this.onGetProData({...intersects_people[0].object.userData},'人员')
          }
        }


   
      


         
      
     
    
     
        

      })

      // 拾取模型坐标

      // renderer.domElement.addEventListener('dblclick',onMouseClick,false);

      function onMouseClick (event){
        const px = event.offsetX
        const py = event.offsetY
        const x = (px / width) * 2 - 1;
        const y = -(py / height) * 2 + 1;
        const mouse = new THREE.Vector2();
        mouse.x = x
        mouse.y = y
        // 创建射线投射器
        const raycaster = new THREE.Raycaster();
         // 从相机发出射线，穿过鼠标点击位置
        raycaster.setFromCamera(mouse, camera);
         // 检测射线与场景中物体的交点
         const changdi = scene.getObjectByName('模型文件')
        const intersects = raycaster.intersectObjects(scene.children, true);
        if (intersects.length > 0) {
          // 获取第一个交点的物体及其世界坐标
          const intersection = intersects[0];
          const object = intersection.object;
          const worldPoint = intersection.point;
          // traverseAndLogPositions(object)
          // const localPoint = getLocalPosition(object,worldPoint)
          console.log('World coordinates:', worldPoint.x, worldPoint.y, worldPoint.z);
        }

      }
      function getLocalPosition(object, worldPoint) {
        const localPoint = new THREE.Vector3();
        localPoint.copy(worldPoint);
        object.worldToLocal(localPoint);
        return localPoint;
      }
      const controls = new OrbitControls(camera, renderer.domElement);
      controls.target.set(50, 30, 0); //与lookAt参数保持一致
      controls.update(); //update()函数内会执行camera.lookAt(controls.target)
      // controls.enableRotate = false; // 禁止旋转

      // controls.enableZoom = false; //禁止缩放
      // //相机位置与观察目标点最小值
      // controls.minDistance = 120;
      // // //相机位置与观察目标点最大值
      // controls.maxDistance = 1000;
      // controls.maxTargetRadius = 400
      controls.mouseButtons = {
        //左键平移
        LEFT: THREE.MOUSE.PAN,
        //滚轮滑动
        MIDDLE: THREE.MOUSE.DOLLY,
        //右键旋转
        RIGHT: THREE.MOUSE.ROTATE,
      };

      // 用不到
      // controls.minZoom = -1;
      // controls.maxZoom = 2;
      // controls.update();
      // controls.minTargetRadius  =
      // controls.touches = {
      //                         ONE: THREE.TOUCH.DOLLY_PAN ,
      //                         TWO: THREE.TOUCH.ROTATE,
      //                     }
      controls.update();


      // 画布跟随窗口变化
      return {
        scene,
        controls,
        renderer,
        camera,
        css2Renderer,
        // composer,
        // outlinePass
      };
    },

    // 向组件添加实时数据
    addProViewData(item) {
      const calc = 10
      const JG = 1
      const { type, data } = item
      if (type === 'location') {
        const { trackList, personId } = data
        // 如果是轨迹
        const [x, y, z] = trackList[0].pos
        this.pointsData.forEach((item, index) => {
          if (item.personId === personId) {
            item.positions.push(x * calc + JG * index, y * calc + JG * index, 3)
          }
        })

        this.handleLine()
      }
      if (type === 'alarm') {
        const { id, personId, alarmName, alarmTime, alarmAddress, alarmContent, deviceId, personName, personType, xyz, bidName, fileUrl } = data
        console.log('deviceId', deviceId);
        const newdeviceId = deviceId.split(',')
        const newalarmTime = dayjs(alarmTime).format('YYYY-MM-DD HH:mm:ss')
        const [x, y, z] = xyz
        this.pointsData.forEach((item, index) => {
          if (item.personId === personId) {
            item.points_waring.push(new THREE.Vector3(x * calc + JG * index, y * calc + JG * index, z + 3))
            item.ids_waring.push(id)
            // 弹出预警
            this.curItemMsg = {
              alarmName,
              alarmTime: newalarmTime,
              alarmAddress,
              alarmContent,
              deviceId: newdeviceId,
              personName,
              personType,
              bidName,
              fileUrl
            }
          }
        })
        this.handleLine()
        // 再次选中预警模型
      
        const GroupYujing =  this.D3data.scene.getObjectByName('预警组')
        const box = GroupYujing.getObjectByName(id)
        const { px, py } = this.getScreenCoordinates(box)
        document.querySelector('#box_people').style.top = 0 + 'px'
        document.querySelector('#box_people').style.left = 100 + 'px'
        document.getElementById('box_people').style.display = "block"
        const WangerMsg = this.setWangerMsg(`${alarmContent}`)
        this.handlePlay()
        setTimeout(() => {
          GroupYujing.remove(WangerMsg) // 这里需要处理
          document.getElementById('box_people').style.display = "none"

        }, 1000 * 10);

        console.log('this.curItemMsg ', this.curItemMsg);


      }
      if (type === 'alarm.broadcast') {
        const { id, personId, alarmName, alarmTime, alarmAddress, alarmContent, deviceId, personName, personType, xyz, } = data
        const GroupYujing =  this.D3data.scene.getObjectByName('预警组')
        const WangerMsg = this.setWangerMsg(`${alarmContent}`)
        this.handlePlay()
        setTimeout(() => {
          GroupYujing.remove(WangerMsg)
        }, 1000 * 10);
      }
      // 添加人员
      if (type === 'uwb_bind') {
        this.$parent.addPeople(data);
      }

    },
    // 多种类型人员
    // setPeopleRadiusPoints(data) {
    //   const TYPE = {
    //     'PBZJ': '评标专家组',
    //     'ZBDL': '招标代理组',
    //     'JFDB': '甲方代表组'
    //   }
    //   data.forEach(item => {
    //     const Group = model.getObjectByName(TYPE[item.type])
    //     const geometry = new THREE.SphereGeometry(0.4, 10, 10); // 半径为1，分段数为32
    //     // 创建材质
    //     const color = new THREE.Color(item.color)
    //     const material = new THREE.MeshBasicMaterial({ color, side: THREE.DoubleSide });
    //     // 创建网格
    //     const circle = new THREE.Mesh(geometry, material);
    //     item.list.forEach((ite) => {
    //       const newCircle = circle.clone()
    //       newCircle.name = ite.id
    //       const { x, y, z } = ite.xyz
    //       newCircle.position.set(x, y, z)
    //       Group.add(newCircle)
    //     })
    //   })
    // },
    initObject3D() {
      const Group = new THREE.Group();
      const Group_wanger = Group.clone()
      const Group_people_PBZJ = Group.clone()
      const Group_people_ZBDL = Group.clone()
      const Group_people_JFDB = Group.clone()
      const Group_people_GZRY = Group.clone()
      const Group_rooms = Group.clone()
      Group_wanger.name = '预警组'
      Group_people_PBZJ.name = '评标专家组'
      Group_people_ZBDL.name = '招标代理组'
      Group_people_JFDB.name = '甲方代表组'
      Group_people_GZRY.name = '工作人员组'
      Group_rooms.name = '场地房间'
     const allMesh = this.D3data.scene.getObjectByName('全部')
     allMesh.add(Group_wanger).add(Group_people_PBZJ).add(Group_people_ZBDL).add(Group_people_JFDB).add(Group_rooms).add(Group_people_GZRY)
    
    },



    // 切换楼层
    handleTabsLouceng(val) {
      const arr = ['1010楼十楼', '十二楼12楼12层']
      const arrText = ['十楼', '十二楼']
      // const prambox = model.children[0] // 场地模型
     
      const changdi = this.D3data.scene.getObjectByName('/gltf/10-12/glt')
      const arrContent = [texture10, texture12]
      const index = arr.findIndex(x => x.includes(val))
      changdi.material.map = arrContent[index]
      this.louceng = arrText[index]
      this.setTabRoomName(arrText[index])
    },

    // 播放音频
    handlePlay() {
      const audioPlayer = this.$refs['audioPlayer']
      audioPlayer.play().then(() => {
        audioPlayer.muted = false;
      }).catch(error => {
        console.error("Error playing audio:", error);
      });

    },
    // 获取标准设备坐标
    // 获取模型在屏幕上的坐标
    getScreenCoordinates(object) {
      const width = this.$refs["D3_dom"].offsetWidth;
      const height = this.$refs["D3_dom"].offsetWidth;
      const vector = new THREE.Vector3();
      // 将模型的世界坐标转换为标准化设备坐标（NDC）
      vector.setFromMatrixPosition(object.matrixWorld);
      vector.project(this.D3data.camera);
      // 将 NDC 坐标转换为屏幕坐标
      const screenX = Math.round((vector.x + 1) * width / 2);
      const screenY = Math.round((1 - vector.y) * height / 2);
      return { px: screenX, py: screenY };
    },
    setWangerMsg(data) {
      this.WangerMsgData = data           // 将css元素添加到模型中
      const DivWangerMsg = this.$refs["wangerMsg"]
      const DivModelDivWangerMsg = new CSS2DObject(DivWangerMsg);
      DivModelDivWangerMsg.name = '警告信息'
      DivModelDivWangerMsg.position.set(800, 340, 0)

      const changdi = this.D3data.scene.getObjectByName('预警组')
      changdi.add(DivModelDivWangerMsg)
      return DivModelDivWangerMsg


    },
    clearCanvas(data = []) { //初始化操作
     const prambox =  this.D3data.scene.getObjectByName('全部')
      while (prambox.children.length > 0) {
        if (prambox.children[0]) {
          // if(prambox.children[0].name === '全部楼层'){
          //   break
          // }
          prambox.remove(prambox.children[0]);
        }
      }
      // this.setRoomName()
      // console.log('prambox',prambox);
      if (data.length <= 0) return
    },
    setTabRoomName(val) {
     
      const roomAll =  this.D3data.scene.getObjectByName('全部楼层')
      roomAll.children.forEach(item => {
        item.visible = false
        if (item.name === val) {
          item.visible = true
        }
      })
    },
    // 切换房间名称
    async setRoomName() {
      
      const prambox = this.D3data.scene.getObjectByName('全部')
      // const room = prambox.getObjectByName('房间')
      const Group = new THREE.Group()
      const GroupRoomAll = Group.clone()
      const GroupRoomRoom10 = Group.clone()
      const GroupRoomRoom12 = Group.clone()
      GroupRoomAll.name = '全部楼层'
      GroupRoomRoom10.name = '十楼'
      GroupRoomRoom12.name = '十二楼'
      GroupRoomAll.add(GroupRoomRoom10).add(GroupRoomRoom12)
      // const groupRoom = model.getObjectByName('全部楼层') // 场地模型
      // const arr = louceng_JSON['十楼'].map(item => {
      //   item.roomName = item.name
      //   return {...item,}
      // })
      // console.log('louceng_JSON',louceng_JSON);
      louceng_JSON['十楼'].forEach(item => {
        const text = createText(item.name, 6)
        text.position.set(item.xl, item.yl, 0)
        GroupRoomRoom10.add(text)
        // console.log('item',item);

      })
      louceng_JSON['十二楼'].forEach(item => {
        const text = createText(item.name, 6)
        text.position.set(item.xl, item.yl, 0)
        GroupRoomRoom12.add(text)
        // console.log('item',item);
      })
      // for (const i in arr) {
      //   const text = createText(arr[i].roomName, 6)
      //   text.position.set(Number(arr[i].xl), arr[i].yl, 0)
      //   groupRoom.add(text);
      // }
      GroupRoomRoom10.visible = true;
      GroupRoomRoom12.visible = false
      prambox.add(GroupRoomAll)
    },


   
   
   
    // 关键帧动画弃用
    keyAnm() {
      const values = points
      const posKF = new THREE.KeyframeTrack('BoxLine2.geometry.attributes.position', times, values)
      // const colorKF = new THREE.KeyframeTrack('BoxLine2.material.color', times, [1,0,0,0,0,1])
      const clip = new THREE.AnimationClip('Action', times.at(-1), [posKF])
      const mixer = new THREE.AnimationMixer(line2);
      const clipAction = mixer.clipAction(clip)
      clipAction.play()
      clipAction.loop = THREE.LoopOnce // 只播放一次
      clipAction.clampWhenFinished = true // 动画播放结束位置
      clipAction.timeScale = 0.5 //播放倍速
      // clipAction.time = 1 // 从第一秒开始播放
      // clipAction.duration = 5 //到多少s结束
      // clipAction.paused = true // 暂停
      // const gui = new GUI()
      // const params = {
      //   time: 0
      // }
      // gui.add(params,'x',0,100).name('x').onChange((value)=>{

      // })
      //   function loop (){
      //     requestAnimationFrame(loop)
      //     const frameT = clock.getDelta()
      //     mixer.update(frameT)
      // }
      // loop()
    },
    //
    addGui() {
      // const gui = new GUI()
      // const {camera,controls} = this.D3data
      // const params = {
      //   x: camera.position.x,
      //   y: camera.position.y,
      //   z: camera.position.z,
      //   resetPosition: function () {
      //     this.x = 5;
      //     this.y = 5;
      //     this.z = 5;
      //   }
      // }
      // gui.add(params, 'x', 0, 300, 1).name('X posittion').onChange((value) => {
      //   camera.position.x = value
      //   // controls.target.set(0, 0, 0); //与lookAt参数保持一致
      //   controls.update(); //update()函数内会执行camera.lookAt(controls.target)
      // })

      // gui.add(params, 'y', 0, 300, 1).name('Y posittion').onChange((value) => {
      //   camera.position.y = value
      //   controls.update();
      // })

      // gui.add(params, 'z', 0, 300, 1).name('Z posittion').onChange((value) => {
      //   camera.position.z = value
      //   controls.update();
      // })
      // gui.add(params, 'resetPosition').name('Reset Position');
    },
    handleTools(TYPE) {
      if (TYPE === 1) {
        console.log( 'this.D3data.camera.position',this.D3data.camera.position );
        if (this.D3data.camera.position.z < 30) return
        this.D3data.camera.position.z -= 10
        this.D3data.camera.position.y += 10
        this.D3data.camera.updateProjectionMatrix();
      }
      if (TYPE === 2) {
        if (this.D3data.camera.position.z > 120) return
        this.D3data.camera.position.y += -10
        this.D3data.camera.position.z += 10
        this.D3data.camera.updateProjectionMatrix();
      }
      if (TYPE === 3) {
        this.$refs['D3_dom'].requestFullscreen()
        // this.D3data.renderer.domElement.requestFullscreen()
      }
    },
    // 播放设备
    handelePlay(item, index) {
      const { deviceId, id } = item
      this.playerIsShow = true
      const params = {
        "deviceId": deviceId[index],
        alarmId: id
      }
      getAlarmPlaybackURLs(params).then(res => {
        if (res.code === 0) {
          this.videoUrl = res.data.url
        }

      })
    },
    // 屏幕坐标转标准设备坐标
    changXY(camera, renderer, outlinePass) {
      const width = this.$refs["D3_dom"].offsetWidth;
      const height = this.$refs["D3_dom"].offsetHeight;
      renderer.domElement.addEventListener('click', function (event) {
        const px = event.offsetX;
        const py = event.offsetY;
        // 屏幕坐标px,py 转WebGL标准设备坐标x,y
        // width ,height 画布宽高度
        const x = (px / width) * 2 - 1;
        const y = -(py / height) * 2 + 1;
        // console.log('x',x);
        // console.log('y',y);
        const raycaster = new THREE.Raycaster();
        raycaster.setFromCamera(new THREE.Vector2(x, y), camera)
        const intersects = raycaster.intersectObjects(model.children)
        if (intersects.length > 0) {
          // console.log(intersects[0]);
          outlinePass.selectedObjects = [model.children];
          // 选中模型的第一个模型，设置为红色
          intersects[0].object.material.color.set(0xff0000);

        }

      })


    },
    handleGoLeft(flg) {
      this.$refs["flexUl"].scrollBy({
        top: 0,
        left: !flg ? 90 : -90,
        behavior: "smooth"
      });
    },
    handleClear() {
      this.D3data.scene.traverse(function (obj) {
        if (obj.isMesh) {
          //判断是否是网格模型
          obj.material.color.set(new THREE.Color("#fff"));
        }
      });
    },
    handleSelect(name) {
      // 0x00FFFFFF
      this.D3data.scene.getObjectByName(name).material.color.set(new THREE.Color("#CD5C5C"));
    },
    debounce(fn, delay) {
      const delays = delay || 500;
      let timer;
      return function () {
        const th = this;
        const args = arguments;
        if (timer) {
          clearTimeout(timer);
        }
        timer = setTimeout(function () {
          timer = null;
          fn.apply(th, args);
        }, delays);
      };
    }
  },

  async mounted() {
    await this.getdata()
    this.D3data = this.initDiv();
    this.initObject3D()
    window.onresize = () => {
      this.$nextTick(() => {
        const width = this.$refs["D3_dom"].offsetWidth;
        const height = this.$refs["D3_dom"].offsetHeight;
        this.D3data.renderer.setSize(width, height);
        this.D3data.css2Renderer.setSize(width, height);
        this.D3data.camera.aspect = width / height;
        this.D3data.camera.updateProjectionMatrix();
      })
    };
    // 渲染循环
    const render = () => {
      // this.group.update(time)
      this.D3data.renderer.render(this.D3data.scene, this.D3data.camera);
      // this.D3data.renderer.render()
      this.D3data.css2Renderer.render(this.D3data.scene, this.D3data.camera);
       // 标志旋转动画
      const Group_rooms =  this.D3data.scene.getObjectByName('场地房间')
      if(Group_rooms && Group_rooms.children.length> 0){
        Group_rooms.children.forEach(el=>{
          el.rotation.y += 0.01
        })
      }
      requestAnimationFrame(render);
    }
    render();

    // this.addGui()
  },
  destroyed() {
    window.onresize = null;
    this.clearCanvas()

  }
};
</script>

<style scoped lang="scss">
$font14: 14px;

.button_box {
  position: absolute;
  top: 10px;
  left: 10px;

}

.lerg {
  position: absolute;
  top: 20px;
  right: 20px;

  >ul {
    display: flex;

    li {
      line-height: 30px;
      margin-right: 10px;
      display: flex;
      align-items: center;
      color: #fff;
     

      img {
        width: 18px;
        height: 18px;
        margin-top: -4px;
        margin-right: 8px;
    
      }

      .radius {
        width: 14px;
        height: 14px;
        border-radius: 50%;
        margin-right: 8px;
      
      }

      &:nth-child(2) .radius {
        background: #68F60C;
      }

      &:nth-child(3) .radius {
        background: #FFC30A;
      }

      &:nth-child(4) .radius {
        background: #EB31D9;
      }
      &:nth-child(5) .radius {
        background: #fff;
      }
    }
  }
}

.tools {
  position: absolute;
  bottom: 20px;
  right: 20px;

  li {
    width: 40px;
    height: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
    border: 1px solid #576479;
    background-color: #20314e;

    &:hover {
      background-color: #2f5c9b;
    }

  }

  .iconfontSvg {
    width: 18px;
    height: 18px;
    fill: #ffffff;
  }
}
#progress-bar {
            position: absolute;
            width: 400px;
            height: 16px;
            top: 50%;
            left: 50%;
            margin-left: -200px;
            margin-top: -8px;
            border-radius: 8px;
            border: 1px solid #009999;
            overflow: hidden;
        }
        #progress{
            height: 100%;
            width: 0px;
            background: #00ffff;
            color: #00ffff;
            line-height: 15px;
        }

</style>
